<template>
  <div class="container">
    <div class="controls">
      <div class="filter-container">
        <span 
          class="filter-text" 
          :class="{ active: resourceType === 'all' }"
          @click="setStatus('all')"
        >所有文件</span>
        <span 
          class="filter-text" 
          :class="{ active: resourceType === 'ppt' }"
          @click="setStatus('ppt')"
        >PPT幻灯片</span>
        <span 
          class="filter-text" 
          :class="{ active: resourceType === 'word' }"
          @click="setStatus('word')"
        >Word文档</span>
      </div>

      <div class="search-container">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索文件名..." 
          class="search-input"
        />
        <img style="margin-right:90px"
          src="@/assets/picture/find.png" 
          class="search-icon" 
          @click="filterResources"
        />
        <button class="btn btn-upload" @click="selectFile">上传资料</button>
        <input type="file" ref="fileInput" @change="handleFileChange" accept=".ppt,.pptx,.doc,.docx" style="display: none" />
      </div>
    </div>

    <table class="resource-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>资料名称</th>
          <th>类型</th>
          <th>更新时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr 
        v-for="(resource, index) in paginatedResources" 
        :key="resource.resource_id" 
        @click="handleSelect(resource)"
        >
          <td>{{ (currentPage - 1) * itemsPerPage + index + 1 }}</td>
          <td>
            <span v-if="!resource.isEditing">{{ resource.resource_name }}</span>
            <input 
              v-else 
              type="text" 
              v-model="resource.newName" 
              @blur="confirmRename(resource)"
              @keyup.enter="confirmRename(resource)"
              class="resource-edit-input"
            />
          </td>
          <td>{{ resource.resource_type }}</td>
          <td>{{ resource.update_time }}</td>
          <td>
            <a class="btn btn-link" :href="resource.resource_url" target="_blank">下载</a>
            <button class="btn btn-rename" @click="startRenaming(resource)">重命名</button>
            <button class="btn btn-delete" @click="deleteResource(resource.resource_id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <PagiNation
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="handlePageChange"
    />

    <div v-if="isLoading" class="loading">加载中...</div>
  </div>
</template>

<script>
import { ref, computed, onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  upload, 
  apiRenameResource, 
  apiDeleteResource,
  fetchResourcesByType, 
  fetchAllResources  
} from '@/services/api';
import PagiNation from '@/components/PagiNation.vue';

export default {
  name: 'T_WordPage',
  components: {
    PagiNation,
  },
  setup(props, context) {
    const router = useRouter();
    const techId = ref(null);
    const token = ref(null);
    const currentPage = ref(1);
    const itemsPerPage = 15; //条数
    const resourceType = ref('all');
    const resources = ref([]);
    const filteredResources = ref([]);
    const searchQuery = ref('');
    const file = ref(null);
    const fileInput = ref(null);
    const isLoading = ref(false); // Add loading state
    const fetchResources = () => {
      if (!techId.value) {
        router.push('/login');
        return;
      }

      isLoading.value = true; // Start loading

      if (resourceType.value !== 'all') {
        fetchResourcesByType(techId.value, resourceType.value, token.value)
          .then((response) => {
            if (response.data.status === 1) {
              resources.value = response.data.data;
              filteredResources.value = resources.value;
              currentPage.value = 1; // Reset to the first page
              console.log(`Fetched ${resources.value.length} resources for type ${resourceType.value}`);
            } else {
              console.error('获取资源失败:', response.data.msg);
              if (response.data.status === 'NOT_LOGIN') {
                router.push('/login');
              }
            }
          })
          .catch((error) => {
            console.error('请求错误:', error);
          })
          .finally(() => {
            isLoading.value = false; // End loading
          });
      } else {
        fetchAllResources(techId.value, token.value)
          .then(([pptResponse, wordResponse]) => {
            const pptFiles = pptResponse.data.data || [];
            const wordFiles = wordResponse.data.data || [];
            resources.value = [...pptFiles, ...wordFiles];
            filteredResources.value = resources.value;
            currentPage.value = 1; // Reset to the first page
            console.log(`Fetched ${resources.value.length} resources for all types`);
          })
          .catch((error) => {
            console.error('请求错误:', error);
          })
          .finally(() => {
            isLoading.value = false; // End loading
          });
      }
    };

    const setStatus = (status) => {
      resourceType.value = status;
      currentPage.value = 1;
      fetchResources();
    };

    const filterResources = () => {
      if (searchQuery.value) {
        filteredResources.value = resources.value.filter(resource =>
          resource.resource_name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      } else {
        filteredResources.value = resources.value;
      }
      currentPage.value = 1; // Reset to the first page
      console.log(`Filtered Resources: ${filteredResources.value.length}`);
    };

    const paginatedResources = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredResources.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredResources.value.length / itemsPerPage) || 1;
    });

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    const startRenaming = (resource) => {
      resource.isEditing = true;
      resource.newName = resource.resource_name;
    };

    const confirmRename = (resource) => {
      if (resource.newName.trim() && resource.newName !== resource.resource_name) {
        apiRenameResource(resource.resource_id, resource.newName)
          .then(response => {
            if (response.data.status === 1) {
              resource.resource_name = resource.newName;
              ElMessage.success('重命名成功！');
            } else {
              ElMessage.error('重命名失败，请重试。');
            }
          })
          .catch(error => {
            console.error('重命名请求错误:', error);
            ElMessage.error('重命名失败，请检查网络或稍后重试。');
          });
      }
      resource.isEditing = false;
    };

    const selectFile = () => {
      if (fileInput.value) {
        fileInput.value.click();
      }
    };

    const handleFileChange = (event) => {
      const selectedFile = event.target.files[0];
      if (!selectedFile) {
        return;
      }
      file.value = selectedFile;
      uploadResource();
    };

    const uploadResource = () => {
      if (!file.value) {
        ElMessage.warning('请选择要上传的文件。');
        return;
      }

      const formData = new FormData();
      formData.append('tech_id', techId.value);
      formData.append('resource_type', getFileType(file.value));
      formData.append('file', file.value);

      upload(formData, token.value) // Pass the token
        .then(response => {
          console.log('文件上传成功:', response.data);
          ElMessage.success('文件上传成功！');
          fetchResources(); // Refresh resource list after successful upload
        })
        .catch(error => {
          console.error('文件上传失败:', error);
          ElMessage.s('文件上传失败，请重试。');
        });
    };

    const getFileType = (file) => {
      const extension = file.name.split('.').pop().toLowerCase();
      if (['ppt', 'pptx'].includes(extension)) {
        return 'ppt';
      } else if (['doc', 'docx'].includes(extension)) {
        return 'word';
      }
      return 'other';
    };
const handleSelect = (resource) => {
  // 转换资源格式匹配父组件需要的结构
  const selectedDoc = {
    id: resource.resource_id,
    name: resource.resource_name,
    type: resource.resource_type === 'word' ? 'document' : 'ppt',
    uploadTime: resource.update_time,
    url: resource.resource_url
  };
 context.emit('document-selected', selectedDoc);  // 使用 context.emit
};

    const deleteResource = async (resourceId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此资源吗？',
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response = await apiDeleteResource(resourceId);
    if (response.data.status === 1) {
      ElMessage.success('资源删除成功');
      resources.value = resources.value.filter(resource => resource.resource_id !== resourceId);
      filteredResources.value = filteredResources.value.filter(resource => resource.resource_id !== resourceId);
      if ((currentPage.value - 1) * itemsPerPage >= filteredResources.value.length && currentPage.value > 1) {
        currentPage.value--;
      }
    } else {
      console.error('删除资源失败:', response.data.msg);
      ElMessage.error('删除失败，请重试。');
    }
  } catch (error) {
    // 用户取消操作自动捕获
  }
};

    onMounted(() => {
      const storedTechId = localStorage.getItem('id');
      const storedToken = localStorage.getItem('token');

      if (storedTechId && storedToken) {
        techId.value = storedTechId;
        token.value = storedToken;
        fetchResources();
      } else {
        console.error('User is not logged in. Redirecting to login page.');
        router.push('/login');
      }
    });

    return {
      techId,
      token,
      currentPage,
      itemsPerPage,
      resourceType,
      resources,
      filteredResources,
      paginatedResources,
      searchQuery,
      setStatus,
      startRenaming,
      confirmRename,
      deleteResource,
      uploadResource,
      filterResources,
      handlePageChange,
      totalPages,
      isLoading,
      file,
      fileInput,
      selectFile,
      handleFileChange,
      handleSelect
    };
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
  margin-bottom: 40px;
}
.resource-table input[type="text"] {
  width: 100%;
  padding: 5px;
  font-size: 14px;
}


.resource-table td:nth-child(1) {
  width: 40px; /* 设置序号列的宽度 */
}

.resource-table td:nth-child(2) {
  width: 240px; /* 设置资料名称列的宽度 */
}

.resource-table td:nth-child(3) {
  width: 50px; /* 设置文件类型列的宽度 */
}

.resource-table td:nth-child(4) {
  width: 150px; /* 设置更新时间列的宽度 */
}

.resource-table td:nth-child(5) {
  width: 200px; /* 设置操作列的宽度 */
}

.controls {
  display: flex; /* Use flexbox */
  justify-content: space-between; 
  align-items: center; /* Vertically center */
  margin-bottom: 20px;
}

.btn  {
  display: inline-block;
  padding: 8px 10px;
  margin: 5px;
  background-color: rgb(236, 241, 253);
  color: #82beff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.btn:hover {
  background-color: #badafc;
  color: rgb(0, 110, 255);
}

.btn-upload  {
  background-color: #125AA2;
  color: #fff;
}

.btn-upload:hover {
  background-color: #3987d4;
  color: white;
}


.filter-container {
  display: flex;
  gap: 10px;
}

.filter-text{
  margin-right: 10px;
  cursor: pointer;
  font-weight: normal;
  padding-bottom: 10px;
  width: 90px;
  text-align: center;
  color: #4d4d4d;
}

.filter-text.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
  margin-bottom: -2px;
}
.search-container {
  display: inline-flex;
  align-items: center;
  margin-left: auto; /* Push the search container to the right */
  position: relative; /* 用于定位搜索图标 */
}

.search-input {
  padding: 10px 40px 10px 10px; /* 给右边留出空间放图标 */
  border: 1px solid #ccc;
  border-radius: 20px; /* 设置圆角 */
  font-size: 16px;
  width: 200px; /* Set search box width */
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}


.resource-table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
}

.resource-table th{
  padding: 10px;
}

.resource-table th,
.resource-table td {
  text-align: center; /* 设置文本居中 */
  border: 1px solid #ddd;
  font-size: 14px;
  color: #4d4d4d;
}

.resource-table th {
  background-color: #f4f4f4;
  color: #333;
  font-weight: bold;
  font-size: 14px;
  color: #4d4d4d;
}

.resource-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.resource-table tbody tr:hover {
  background-color: #e9ecef;
}

.resource-table a {
  text-decoration: none;
}
.btn-link{
background-color: #3A88D5;
color: white;
}
.resource-edit-input {
  width: 100%;
  padding: 5px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box; /* 包含内边距和边框在宽度计算中 */
}

/* Pagination */
.pagination {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination .btn {
  padding: 8px 12px;
  margin: 0 10px;
  cursor: pointer;
  border: none;
  background-color: #2196f3;
  color: white;
  border-radius: 4px;
}

.pagination .btn:disabled {
  background-color: #b0c4de;
  cursor: not-allowed;
}

.pagination span {
  margin: 0 10px;
  font-weight: bold;
}

/* Loading indicator */
.loading {
  text-align: center;
  font-size: 18px;
  color: #555;
  margin-top: 20px;
}
</style>
